package com.benson.common.common.interceptor;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.benson.common.common.constants.Constants;
import com.benson.common.common.util.CommonUtil;
import com.google.common.net.HttpHeaders;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * jwt拦截器
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader(HttpHeaders.AUTHORIZATION);
        //设置全局变量，在feign调用异步请求时，添加token认证 -> FeignHeaderInterceptor
        Optional.ofNullable(authorization)
                .filter(StrUtil::isNotBlank)
                .ifPresent(token -> {
                    /** 解析token 获取当前登录用户信息 */
                    Claims claims = CommonUtil.parseJWT(token);
                    if (ObjectUtil.isNotNull(claims)) {
                        System.setProperty(Constants.CURRENT_USER_ID,claims.get("user_id").toString());
                        System.setProperty(HttpHeaders.AUTHORIZATION, token);
                    }
                });
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //拦截器结束后，删除token
        System.clearProperty(Constants.CURRENT_USER_ID);
        System.clearProperty(HttpHeaders.AUTHORIZATION);
    }
}